<?php

declare (strict_types=1);

namespace app\store\model;

use app\common\model\Exchange as ExcahngeModel;
use app\common\enum\exchange\LogStausType as LogStausTypeEnum;
use app\common\enum\exchange\ValidityType as ValidityTypeEnum;

/**
 * 优惠券模型
 * Class Coupon
 * @package app\store\model
 */
class Exchange extends ExcahngeModel
{
    /**
     * 获取列表记录
     * @param array $param
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getList(array $param = []): \think\Paginator
    {
        // 检索查询条件
        $filter = $this->getFilter($param);
        // 查询列表数据
        return $this->where($filter)
            ->order(['createtime' => 'desc'])
            ->paginate(15);
    }

    /**
     * 检索查询条件
     * @param array $param
     * @return array
     */
    private function getFilter(array $param = []): array
    {
        // 默认查询条件
        $param = $this->setQueryDefaultValue($param, ['search' => '']);
        // 检索查询条件
        $filter = [];
        !empty($param['search']) && $filter[] = ['name', 'like', "%{$param['search']}%"];
        return $filter;
    }

    /**
     * 添加新记录
     * @param array $data
     * @return bool|false
     */
    public function add(array $data): bool
    {
        $data['store_id'] = self::$storeId;
        return $this->save($this->createData($data));
    }

    /**
     * 更新记录
     * @param array $data
     * @return bool
     */
    public function edit(array $data): bool
    {
        return $this->save($this->createData($data)) !== false;
    }

    /**
     * 创建数据
     * @param array $data
     * @return array
     */
    private function createData(array $data): array
    {
        $data['store_id'] = self::$storeId;
        if(isset($data['start_time'])){
            $data['start_time'] = strtotime($data['start_time']);
        }
        if(isset($data['end_time'])){
            $data['end_time'] = strtotime($data['end_time']);
        }
        $data['createtime'] = time();
//        // 折扣券记录有效期
//        // 领取后生效
//        if ($data['expire_type'] == ExpireTypeEnum::RECEIVE) {
//            $data['start_time'] = $data['end_time'] = 0;
//        } // 固定时间
//        elseif ($data['expire_type'] == ExpireTypeEnum::FIXED_TIME) {
//            $times = between_time($data['betweenTime']);
//            $data['start_time'] = $times['start_time'];
//            $data['end_time'] = $times['end_time'] + (86400 - 1);
//            $data['expire_day'] = 1;
//        }
//        // 适用范围
//        if ($data['apply_range'] == ApplyRangeEnum::ALL) {
//            $data['apply_range_config'] = [];
//        }
        return $data;
    }

    /**
     * 删除记录 (软删除)
     * @return bool
     */
    public function setDelete(): bool
    {
        return $this->save(['is_delete' => 1]) !== false;
    }
}
